package com.example.activiti7.domain.model.req;

import com.example.activiti7.domain.model.resp.PrintFriendliness;
import io.swagger.v3.oas.annotations.media.Schema;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.UUID;

/**
 * request基类
 * 使用时引用
 * <dependency>
 * <groupId>org.springframework.boot</groupId>
 * <artifactId>spring-boot-starter-validation</artifactId>
 * </dependency>
 * <p>
 * *示例代码：
 * *@Data
 * *public class LoginReq extends BaseRequest {
 * *@NotBlank(message = "用户名不能为空")
 * *private String username;
 * *@NotBlank(message = "密码不能为空")
 * *private String password;
 * *}
 * *业务代码：req.validate()
 * *由全局异常进行IllegalArgumentException异常捕获统一处理即可
 *
 * @author PD
 */
public abstract class BaseRequest extends PrintFriendliness {
    private static final long serialVersionUID = -7140385409591586152L;

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
    /**
     * 请求ID
     */
    @Schema(description = "请求唯一ID(默认为uuid)")
    private String requestId = UUID.randomUUID().toString();

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public void validate() {
        StringBuilder errorMsg = new StringBuilder();
        Set<ConstraintViolation<BaseRequest>> violations = VALIDATOR.validate(this);
        if (violations != null && violations.size() > 0) {
            for (ConstraintViolation<BaseRequest> violation : violations) {
                errorMsg.append(violation.getPropertyPath()).append(":").append(violation.getMessage()).append("|");
            }
            throw new IllegalArgumentException(errorMsg.substring(0, errorMsg.length() - 1));
        }
    }
}
